import numpy as np
import matplotlib.pyplot as plt

def cosine_similarity(p1, p2):
    return np.dot(p1, p2) / (np.linalg.norm(p1) * np.linalg.norm(p2))

def cosine_distance(p1, p2):
    return 1 - cosine_similarity(p1, p2)

# 创建数据点
theta = np.linspace(0, 2*np.pi, 100)
r = np.linspace(0, 1, 50)
R, Theta = np.meshgrid(r, theta)
X = R * np.cos(Theta)
Y = R * np.sin(Theta)

# 选择两个向量
v1 = np.array([0.8, 0.6])
v2 = np.array([0.6, -0.8])

# 计算余弦距离
Z = np.zeros_like(X)
for i in range(X.shape[0]):
    for j in range(X.shape[1]):
        p = np.array([X[i,j], Y[i,j]])
        Z[i,j] = cosine_distance(p, v1)

# 绘制等高线图
plt.figure(figsize=(10, 8))
plt.contourf(X, Y, Z, levels=20, cmap='viridis')
plt.colorbar(label='Cosine Distance from v1')
plt.quiver(0, 0, v1[0], v1[1], color='r', scale=5, label='v1')
plt.quiver(0, 0, v2[0], v2[1], color='b', scale=5, label='v2')
plt.title('Cosine Distance Visualization')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.axis('equal')
plt.show()

print(f"Cosine distance between v1 and v2: {cosine_distance(v1, v2):.2f}")